package com.lagou.edu.mvcframework.pojo;

import com.lagou.edu.mvcframework.interceptor.HandlerInterceptor;
import org.apache.commons.lang3.ObjectUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName HandlerExecutionChain
 * @Description TODO
 * @Auth ying.xiao
 * @Date 2021/2/23
 * @Version 1.0.0
 */
public class HandlerExecutionChain {

    private final Object handler;

    private HandlerInterceptor[] interceptors;

    private List<HandlerInterceptor> interceptorList;

    public HandlerExecutionChain(Object handler,  HandlerInterceptor... interceptors) {
        this.handler = handler;
        this.interceptors = interceptors;
    }

    public boolean applyPreHandle(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HandlerInterceptor[] interceptors = getInterceptors();
        if (null!=interceptors && !ObjectUtils.isEmpty(interceptors)) {
            for (int i = 0; i < interceptors.length; i++) {
                HandlerInterceptor interceptor = interceptors[i];
                if(null != interceptor){
                    if (!interceptor.preHandle(request, response, this.handler)) {
                        return false;
                    }
                }
            }
        }
        return true;
    }

    public Object getHandler() {
        return handler;
    }

    public HandlerInterceptor[] getInterceptors() {
        return interceptors;
    }

    public void setInterceptors(HandlerInterceptor[] interceptors) {
        this.interceptors = interceptors;
    }

    public List<HandlerInterceptor> getInterceptorList() {
        return interceptorList;
    }

    public void setInterceptorList(List<HandlerInterceptor> interceptorList) {
        this.interceptorList = interceptorList;
    }
}
